const readline = require('readline');
const fs = require('fs');
const util = require('util');
const puppeteer = require('puppeteer');
const exec = util.promisify(require('child_process').exec);

const config = {
    account: 'gitee账户',
    password: '密码',
    url: 'Gitee Pages服务页面网址'  // 例如，https://gitee.com/leazer/blog/pages
}

function checkType(key, type) {
    let temp = Object.prototype.toString.call(key).toLowerCase();
    if (temp.indexOf(type) > 6) {
        return true;
    }
    return false;
}

function getLocalTime() {
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let hour = date.getHours();
    let minute = date.getMinutes();
    let second = date.getSeconds();
    return `${year}/${month}/${day} ${hour}:${minute}`;
}

function showMenu() {
    console.log(`
---------------命令手册-----------------------
|  help            :     查看命令手册        |
|  ls              :     查看所有文章        |
|  look [id]       :     查看某文章          |
|  del [id]        :     删除某文章          |
|  make [name]     :     创建文章            |
|  commit          :     将变动提交到远程库  |
|  update          :     更新gitee pages     |
|  q               :     退出                |
----------------------------------------------        
        `);
}

function showArticleList() {
    let data = fs.readFileSync('./js/data.js');
    let str = data.toString().split('=')[1].trim();
    let list = JSON.parse(str);
    for (let i = 0; i < list.length; i++) {
        console.log('------------------------');
        console.log(`序号：${i+1}`);
        console.log(`标题：${list[i].name}`);
        console.log(`时间：${list[i].time}`);
    }
}

function lookArticle(key) {
    let data = fs.readFileSync('./js/data.js');
    let str = data.toString().split('=')[1].trim();
    let list = JSON.parse(str);
    if (/^\d*$/.test(key)) {
        let id = parseInt(key);
        if (id <= 0 || id > list.length) {
            console.log('提示：没有此序号对应的文章！！！');
        } else {
            let name = list[id - 1].name;
            let content = fs.readFileSync(`./article/${name}.html`);
            console.log('------------------------');
            console.log(content.toString());
        }
    } else {
        for (let i = 0; i < list.length; i++) {
            if (list[i].name == key) {
                let content = fs.readFileSync(`./article/${key}.html`);
                console.log('------------------------');
                console.log(content.toString());
                return;
            }
        }
        console.log('提示：未找到此文章！！！');
    }
}

function deleteArticle(key) {
    let data = fs.readFileSync('./js/data.js');
    let str = data.toString().split('=')[1].trim();
    let list = JSON.parse(str);
    if (/^\d*$/.test(key)) {
        let id = parseInt(key);
        if (id <= 0 || id > list.length) {
            console.log('提示：没有此序号对应的文章！！！');
        } else {
            let name = list[id - 1].name;
            try {
                list.splice(id - 1, 1);
                fd = fs.openSync(`./js/data.js`, 'w+');
                fs.writeSync(fd, `let articles = ${JSON.stringify(list)}`);
                fs.closeSync(fd);
                fs.unlinkSync(`./article/${name}.html`);
                console.log(`提示：《${name}》删除成功！！！`);
            } catch (err) {
                console.log('提示：删除失败！！！');
            }
        }
    } else {
        for (let i = 0; i < list.length; i++) {
            if (list[i].name == key) {
                try {
                    list.splice(i, 1);
                    fd = fs.openSync(`./js/data.js`, 'w+');
                    fs.writeSync(fd, `let articles = ${JSON.stringify(list)}`);
                    fs.closeSync(fd);
                    fs.unlinkSync(`./article/${key}.html`);
                    console.log(`提示：《${key}》删除成功！！！`);
                } catch (err) {
                    console.log('提示：出现错误！！！');
                }
                return;
            }
        }
        console.log('提示：未找到此文章！！！');
    }
}

function makeArticle(key) {
    if (!/^[^?“”\/\\<>*|:]+$/.test(key)) {
        console.log('提示：不允许包含? “ ”/ \\ < > * | : ');
        return;
    } else {
        try {
            let data = fs.readFileSync('./js/data.js');
            let str = data.toString().split('=')[1].trim();
            let list = JSON.parse(str);
            for (let i = 0; i < list.length; i++) {
                if (key == list[i].name) {
                    console.log('提示：文章名称请勿重复！！！');
                    return;
                }
            }
            let content = `\
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${key}</title>
    <link rel="stylesheet" type="text/css" href="../css/article.css">
</head>
<body>
<main id="main">
<article>
<!-- 内容区 -->

<h1>标题</h1>
<img src="../image/004.jpg" width="100%">
<blockquote>图片请存储到./image文件夹下</blockquote>
<p>这是模板文章，标记演示如下，<em>强调</em>，<del>删除</del></p>
<p><a href="https://lzsjl.top/">lz小站</a></p>
<p>下面是代码模块的写法</p>
<pre>
<code>#include &lt;iostream&gt;
using namespace std;
int main() {
    cout<<"leazer's world";
    return 0;
}
</code>
</pre>

<!-- 内容区 -->
</article>
</main>
<footer id="footer">
    Copyright © leazer
</footer>
</body>
</html>`;
            let fd = fs.openSync(`./article/${key}.html`, 'w+');
            fs.writeSync(fd, content.trim());
            fs.closeSync(fd);

            list.unshift({
                "name": key,
                "url": `article/${key}.html`,
                "time": getLocalTime()
            });
            fd = fs.openSync(`./js/data.js`, 'w+');
            fs.writeSync(fd, `let articles = ${JSON.stringify(list)}`);
            fs.closeSync(fd);
            console.log(`提示：《${key}》创建成功，路径为“article/${key}.html”`);
        } catch (err) {
            console.log('提示：出现错误！！！');
        }
    }
}

async function updatePages() {
    console.log('提示：更新操作准备中，请勿进行其它操作（如长时间没有反馈，请尝试按下回车键）！！！');
    const browser = await puppeteer.launch({
        headless: true,
    });
    const page = await browser.newPage();
    await page.goto('https://gitee.com/login');
    // 1. 选中账号控件
    let accountElements = await page.$x('//*[@id="user_login"]') // 此处使用 xpath 寻找控件，下同
    // 2. 填入账号
    await accountElements[0].type(config.account)
    // 3. 选中密码控件
    let pwdElements = await page.$x('//*[@id="user_password"]')
    // 4. 填入密码
    await pwdElements[0].type(config.password)
    // 5. 点击登录
    let loginButtons = await page.$x('//*[@id="new_user"]/div[2]/div/div/div[4]/input')
    await loginButtons[0].click()
    // 6. 等待登录成功
    await page.waitFor(1000)
    await page.goto(config.url);
    // 7.1. 监听步骤 7 中触发的确认弹框，并点击确认
    await page.on('dialog', async dialog => {
        console.log('确认更新')
        dialog.accept();
    })
    // 7. 点击更新按钮，并弹出确认弹窗
    let updateButtons = await page.$x('//*[@id="pages-branch"]/div[7]')
    await updateButtons[0].click()
    // 8. 轮询并确认是否更新完毕
    while (true) {
        await page.waitFor(2000)
        try {
            // 8.1 获取更新状态标签
            deploying = await page.$x('//*[@id="pages_deploying"]')
            if (deploying.length > 0) {
                console.log('更新中...')
            } else {
                console.log('更新完毕')
                break;
            }
        } catch (error) {
            break;
        }
    }
    await page.waitFor(500);
    // 10.更新完毕，关闭浏览器
    browser.close();
    console.log('提示：按下回车键返回到命令行！！！');
    return;
}

async function commitArtcile() {
    console.log('提示：提交变动操作准备中，请勿进行其它操作！！！');
    await exec('git add *');
    console.log('提示：全部add成功！！！');
    await exec('git commit -m "添加新文章"');
    console.log('提示：commit成功！！！');
    await exec('git push origin master');
    console.log('提示：推送到远程库成功！！！');
    console.log('提示：按下回车键返回到命令行！！！');
    return;
}

function beginQuery() {
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    rl.setPrompt('输入命令>>>> ');
    rl.prompt();
    rl.on('line', function(line) {
        let temp = line.trim().toLowerCase().split(/\s+/);
        if(temp[0] == 'help') {
            showMenu();
        }else if (temp[0] == 'ls') {
            showArticleList();
        } else if (temp[0] == 'look') {
            lookArticle(temp[1]);
        } else if (temp[0] == 'del') {
            deleteArticle(temp[1]);
        } else if (temp[0] == 'make') {
            let name = '';
            for (let i = 1; i < temp.length; i++) {
                if (i == temp.length - 1) {
                    name += temp[i];
                } else {
                    name += temp[i] + ' ';
                }
            }
            makeArticle(name);
        } else if (temp[0] == 'commit') {
            commitArtcile();
        } else if (temp[0] == 'update') {
            updatePages();
        } else if (temp[0] == 'q') {
            console.log('已退出');
            rl.close();
        } else {
            console.log('提示：请输入正确的命令！！！')
        }
        rl.prompt();
    });
    rl.on('close', function() {
        process.exit(0);
    });

}



(function() {
    showMenu();
    beginQuery();
})();